package servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tool.DataFileHandler;
import tool.ParsingMonitor;

import com.jspsmart.upload.*;

/**
 * This servlet deal with the energy height file upload event.
 * 
 * TODO: In this version, it doesn't contain exception handle process when user
 * upload a invalid file
 */
@SuppressWarnings("serial")
public class FileUpload extends HttpServlet {
	
	/**
	 * Constructor of the object.
	 */
	public FileUpload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * 
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. This method is called when a form has
	 * its tag value method equals to post. <p/>
	 * 
	 * It mainly receives user's data file and stores the file to "upload"
	 * folder
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * 
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// initialization
		SmartUpload smartUpload = new SmartUpload();
		smartUpload.initialize(getServletConfig(), request, response);

		// max file size: 1M
		// smartUpload.setTotalMaxFileSize(1000000);

		// smartUpload.setAllowedFilesList("dat");

		// upload
		try {
			smartUpload.upload();

			Date date = new Date();
			String filename = String.valueOf(date.getTime()) + ".ht";

			File file = smartUpload.getFiles().getFile(0);
			file.saveAs(DataFileHandler.DATA_FOLDER + "/" + filename,
					SmartUpload.SAVE_VIRTUAL);

			String realPath = request.getSession().getServletContext()
					.getRealPath("");
			String dataFolder = realPath + DataFileHandler.DATA_FOLDER;

			boolean valid = DataFileHandler.checkHTFileAndCache(dataFolder
					+ "/" + filename);

			if (!valid) {
				request.getSession().setAttribute("message",
						"The format of the file your uploaded is invalid!");
				response.sendRedirect("error.jsp");
			} else {
				String select = smartUpload.getRequest().getParameter("select");

				java.io.File javaFolder = new java.io.File(dataFolder
						+ DataFileHandler.DATA_PARSED + "/" + select);
				if (ParsingMonitor.contains(select)) {
					request.getSession().setAttribute("select", select);
					request.getSession().setAttribute("filename", filename);					
					request.getRequestDispatcher("waiting.jsp").forward(request, response);
					
					return;
				} else if (!javaFolder.exists()) {
					new Thread(new ParsingMonitor(dataFolder, select) {
					}).start();

					request.getSession().setAttribute("select", select);
					request.getSession().setAttribute("filename", filename);					
					request.getRequestDispatcher("waiting.jsp").forward(request, response);
					
					return;
				}

				response.sendRedirect("CT-IANP.jsp?filename=" + filename
						+ "&select=" + select);
			}
		} catch (SmartUploadException e) {
			request.getSession().setAttribute("message", e.getMessage());
			response.sendRedirect("error.jsp");
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
